package com.scl.cloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

//@Component
public class UrlRedirectFilter extends ZuulFilter {


    /**
     * 重定向的规则,根据key来重定向到val.
     */
    private static Map<String, String> urlMap = new HashMap<>();

    static {
        urlMap.put("/api/test/index", "/microservice-provider-user/index/a");
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String url = request.getRequestURI();
        String[] split = url.split("/", 3);
        ctx.put(FilterConstants.REQUEST_URI_KEY, "/user/index/1");
        ctx.put(FilterConstants.SERVICE_ID_KEY, "microservice-provider-user");
        return null;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    //filterOrder：过滤的顺序
    @Override
    public int filterOrder() {
        return Integer.MAX_VALUE;
    }

    /* (non-Javadoc)filterType：返回一个字符串代表过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
                    pre：路由之前
                    routing：路由之时
                    post： 路由之后
                    error：发送错误调用
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
}